import {
  mapState,
  mapMutations,
  mapActions
} from "vuex";

import {
  getmessage_count,
  LtLongIn,
  get_threetimes_addmoneywindow,
  get_custom_push_log,
  close_custom_push_log,
  show_login_window_new
} from "@/assets/api/userCenterApi";
import MiddleUtil from "@/assets/utils/MiddleUtil";

import {
  getUserActivity,
  getwendawindow,
} from "@/assets/api/indexApi";

import {
  getDiffDay
} from "@/assets/utils/utils.js";

import GoEasy from "goeasy";




function getShowMessage(item) {
  if (item.extendedData == 11) return "[图片]";
  else if (item.extendedData == 111) return "[表情]";
  else return item.message;
}


export default {
  data() {
    return {
      CouponShow: false,
      CouponGetType: 2,
      getAdminCoupon: 0,
      getDiscountSwitch: true,
      myMusic: null,

      showLeafType: 1,
      moenyShow: false,
      leafNum: 0,
      leafPopup: false,

      showHuoDongModel: false,
      showHuoDongModelData: '',

      customPushLogShow: false,
      customPushLogObj: null,

      selectPositionShow: false,

      UserActivity30Obj: null,
      UserActivity30Show: false
    };
  },
  computed: {
    ...mapState("common", {
      userInfo: (state) => state.userInfo,
      // zim: (state) => state.zim,
      goeasyObj: (state) => state.goeasyObj,
    }),
  },
  mounted() {
    let that = this
    if (this.goeasyObj) {
      try {
        this.goeasyObj.disconnect({
          onSuccess: function () {
            that.openWebPage();
          },
          onFailed: function (error) {
            console.log(error)
            console.log("Failed to disconnect GoEasy, code:" + error.code + ",error:" + error.content);
          }
        });
      } catch (error) {
        this.goeasyObj = null
        this.openWebPage();
      }
    } else {
      this.openWebPage();
    }
    this.myMusic = document.getElementById("soundAudio")

  },
  methods: {
    ...mapMutations("common", [
      "set_messageCount",
      "updata_ConversationList",
      "set_goeasyObj",
      "set_vipNoTimeShow"
    ]),
    ...mapMutations("quiz", ["set_entering"]),
    ...mapActions("common", [
      "createZIM",
      "ZIMLogin",
      "getUserInfo2",
      "getUserInfo",
    ]),



    // 打开页面检查是否登录，登录后做相应处理
    openWebPage(is = false) {

      if (localStorage.getItem("token")) {
        this.getmessage_count();
        let that = this;
        setTimeout(() => {
          that.getUserInfo2()
            .then((user) => {
              if (user) {
                that.GoEasy(user);
                //半月及以上时间未登录的用户赠送1000小竹叶
                that.LtLongIn()
                // 获取行为分析统计月度活跃数据-超过3次则赠送2000小竹叶
                that.get_threetimes_addmoneywindow()
                // 检查VIP有没有过期
                that.checkVip();
                // 活动弹窗
                this.show_login_window()
                // viponly弹窗
                that.get_custom_push_log()
                // 一定条件下登陆zego
                if (is) {
                  // that.zegeLogin()
                }
                // if (!user.prevtime) that.selectPositionShow = true
                // if (that.$route.path == '/cswd') {
                //   // 检查有没有获取到优惠券
                //   that.getwendawindow();
                // if (user.activity_reward == '30') that.getDiscount();
                // }
              }
            })
            .catch(() => {});
        }, 100);
      }
    },

    async get_custom_push_log() {
      const res = await get_custom_push_log({})
      if (res.code == 1 && res.data !== null) {
        this.customPushLogShow = true
        this.customPushLogObj = res.data
      }
    },

    goVipOnlyDetail(is = true) {
      this.customPushLogShow = false
      close_custom_push_log({
        // id: this.customPushLogObj.id
      })
      if (is)
        this.$router.push({
          path: '/viponly/' + this.customPushLogObj.url + '.html'
        })

    },

    async show_login_window() {
      const res = await show_login_window_new({})
      if (res.code == 1) {
        // this.showHuoDongModelData = 'https://xzcs-video.oss-cn-beijing.aliyuncs.com/pc/viponly/%E4%BF%A1%E5%B0%81%E5%BC%B9%E7%AA%97.png?v=1'
        this.showHuoDongModelData = res.data.login_window
        // let loginTipShow = localStorage.getItem("loginTipShow2");


        let ifresultTime = false

        const lastTime = localStorage.getItem('loginlastTime') ? parseInt(localStorage.getItem('loginlastTime'), 10) : null;
        const currentTime = Date.now();

        if (lastTime === null) {
          // 没有存储的时间，返回 true 
          ifresultTime = true;
        } else {
          const twoDaysInMilliseconds = 2 * 24 * 60 * 60 * 1000;
          // 有存储的时间，检查是否超过两天（2天 = 2 * 24 * 60 * 60 * 1000 毫秒）
          if ((currentTime - lastTime) > twoDaysInMilliseconds) {
            // 超过两天，返回 true 
            ifresultTime = true;
          } else {
            // 没有超过两天，返回 false
            ifresultTime = false;
          }
        }

        this.showHuoDongModel = ifresultTime
        console.log(this.showHuoDongMode)
      }
    },


    async LtLongIn() {
      const res = await LtLongIn({})
      if (res.data.is_show == 1) {
        this.leafPopup = true;
        this.showLeafType = 1;
        this.leafNum = 1000;
        if (this.leafPopup) {
          const res2 = await getUserActivity({
            activity_id: 2
          })
          this.moenyShow = true
        }
      }
    },

    async get_threetimes_addmoneywindow() {
      const res = await get_threetimes_addmoneywindow({})
      if (res.data.is_show == 1) {
        this.leafPopup = true;
        this.showLeafType = 2;
        this.leafNum = 2000;
        if (this.leafPopup) {
          const res2 = await getUserActivity({
            activity_id: 3
          })
          this.moenyShow = true
        }
      }
    },



    // 去掉奖励弹窗
    async getDiscount() {

      if (this.getDiscountSwitch == false) return;
      this.getDiscountSwitch = false;
      const res = await getUserActivity({
        activity_id: 31,
      });
      // const res = {
      //   code: 1,
      //   data: {
      //     createtime: 1744337187,
      //     end_time: 0,
      //     go_id: 0,
      //     go_url: "/user/mycoupon",
      //     id: 31,
      //     is_del: 0,
      //     is_hot: 0,
      //     is_outside: 0,
      //     name: "新人活动（新版）",
      //     pic: "https://xzcs-video.oss-cn-beijing.aliyuncs.com/uploads/20250411/4c5cbc2eed23ce4a3f8a363cbb9f1c4f.gif",
      //     pic2: "",
      //     start_time: 0,
      //     status: 1,
      //     type: 1,
      //     updatetime: 1744337580,
      //   }
      // }
      if (res.code == 1) {
        this.UserActivity30Obj = res.data;
        this.UserActivity30Show = true
        this.getDiscountSwitch = true;
      }

    },

    // 获取问答优惠券
    async getwendawindow() {
      const res = await getwendawindow({});
      if (res.code == 1 && res.data > 0) {
        this.getAdminCoupon = res.data;
        this.CouponShow = true;
      }
    },

    zegeLogin() {
      let that = this
      this.createZIM()
        .then((zim_x) => {
          that.zim = zim_x
          let zimStatus =
            localStorage.getItem("zimStatus");
          if (!zimStatus) that.getZIM();
        })
        .catch(() => {});
    },

    // GoEasy 消息推送
    GoEasy(user) {
      this.set_goeasyObj(
        GoEasy.getInstance({
          host: "hangzhou.goeasy.io", //新加坡host：singapore.goeasy.io
          appkey: "BC-2d04526a2e3843e1a155de771785533c", //替换为您的应用appkey
          // appkey: "BC-8cf1d9c37dda45c18bbdbf13b2ca6cda", //替换为您的应用appkey
          modules: ["pubsub"],
        })
      );

      let that = this;
      // console.log(this.goeasyObj);
      //建立连接
      this.goeasyObj.connect({
        onSuccess: function () {
          //连接成功
          console.log("GoEasy connect successfully."); //连接成功
        },
        onFailed: function (error) {
          //连接失败
          console.log(
            "Failed to connect GoEasy, code:" +
            error.code +
            ",error:" +
            error.content
          );
        },
      });
      //订阅消息
      this.goeasyObj.pubsub.subscribe({
        channel: user.id, //替换为您自己的channel
        onMessage: function (message) {
          //收到消息
          console.log(
            "收到消息goeasy, Channel:" +
            message.channel +
            " content:" +
            message.content
          );
          if (message.content == 1) {
            setTimeout(() => {
              that.getmessage_count();
            }, 800);
          } else {
            // that.
            let data = JSON.parse(message.content);
            console.log(data)
            if (data && data.type) {
              if (data.type == 2) {
                that.set_entering(data.entering);
              }
              if (data.type == "askClose") {
                data.is = false;
                MiddleUtil.$emit("askClose", data);
              }
              if (data.type == "revokeMsg") {
                data.is = true;
                MiddleUtil.$emit("askClose", data);
              }
              if (data.type == "service_message") {
                // if (that.$route.name != "service-servicechat") {
                //   that.musicPlay()
                //   let notify = that.$notify({
                //     customClass: "service-notify",
                //     title: data.username,
                //     message: getShowMessage(data),
                //     position: "bottom-right",
                //     duration: 10000,
                //     onClick: function () {
                //       notify.close();
                //       that.$router.push({
                //         path: "/service/servicechat",
                //       });
                //     },
                //   });
                // }
              }
              if (data.type == "cswd_message") {
                if (that.$route.name != "chat-id") {
                  that.musicPlay()
                  let notify = that.$notify({
                    customClass: "service-notify",
                    title: '用户发消息了',
                    message: '点击查看',
                    position: "bottom-right",
                    duration: 10000,
                    onClick: function () {
                      notify.close();
                      that.$router.push({
                        path: "/chat/" + data.quiz_id,
                      });
                    },
                  });
                }
              }
            }
          }
        },
        onSuccess: function () {
          console.log("Channel订阅成功。", user.id);
        },
        onFailed: function (error) {
          console.log(
            "Channel订阅失败, 错误编码：" +
            error.code +
            " 错误信息：" +
            error.content
          );
        },
      });
    },

    getZIM() {
      let that = this;
      // 注册监听“运行时错误信息”的回调
      this.zim.on("error", function (zim, errorInfo) {
        // console.log("error", errorInfo.code, errorInfo.message);
      });

      // 更新会话列表
      this.zim.on("conversationChanged", function (zim, {
        infoList
      }) {
        console.log("更新会话列表conversationChanged", infoList);

        that.updata_ConversationList({
          infoList: infoList,
          zim: that.zim
        });
      });

      // 注册监听“网络连接状态变更”的回调
      this.zim.on(
        "connectionStateChanged",
        function (zim, {
          state,
          event,
          extendedData
        }) {
          // console.log(
          //     "connectionStateChanged",
          //     state,
          //     event,
          //     extendedData
          // );
          // 当长时间网络连接断开导致SDK内部登出时，需要重新登录
          if (state == 0 && event == 3) {
            // zim.login(userInfo, token);
            console.log("网络连接状态变更");
            that.ZIMLogin(that.zim).then((zim_l) => {
              that.zim = zim_l;
            });
          }
        }
      );

      // 注册监听“令牌即将过期”的回调
      this.zim.on("tokenWillExpire", function (zim, {
        second
      }) {
        // console.log("令牌即将过期", second);
        // 可以在这里调用 renewToken 接口来更新 token
        // 新 token 生成可以参考上文
        let token = localStorage.getItem("zegoToken");
        localStorage.removeItem("zegoToken");
        zim.renewToken(token)
          .then(function ({
            token
          }) {
            // 更新成功
            localStorage.setItem("zegoToken", token);
            that.ZIMLogin(that.zim).then((zim_l) => {
              that.zim = zim_l;
            });
          })
          .catch(function (err) {
            // 更新失败
            that.ZIMLogin(that.zim).then((zim_l) => {
              that.zim = zim_l;
            });
          });
      });
      // this.ZIMLogin(this.zim).then((zim_l) => {
      //   this.zim = zim_l;
      // });
    },

    // 会员改了现在是问答会员
    checkVip() {
      let vipCloseTime = window.localStorage.getItem("vipCloseTime");
      if (this.userInfo && this.userInfo.is_gpt_vip > 0) {
        let day = getDiffDay(
          this.userInfo.gpt_vip_end_time_text,
          Date.now()
        );
        let diffDay = 7;
        if (
          day > 0 &&
          day < diffDay &&
          (!vipCloseTime || vipCloseTime == "0")
        ) {
          this.set_vipNoTimeShow(true)
          // this.$confirm(
          //   `您的问答会员将于<span style="color: #FA5555;">${this.userInfo.gpt_vip_end_time_text}</span>到期`,
          //   "提示", {
          //     confirmButtonText: "朕知道了",
          //     dangerouslyUseHTMLString: true,
          //     showCancelButton: false,
          //   }
          // ).then(() => {
          //   window.localStorage.setItem("vipCloseTime", "1");
          // });
        }

        if (day >= diffDay) {
          window.localStorage.setItem("vipCloseTime", "0");
        }
      }
    },


    // 获取未读消息
    async getmessage_count() {
      const res = await getmessage_count({});
      if (res.code == 1) {
        this.set_messageCount(res.data);
      }
    },

    musicPlay() {
      this.stopMusic() // 先关闭音乐
      this.myMusic.play() // 播放音乐
    },
    stopMusic() {
      this.myMusic.load()
    }
  }
};
